<template>
	<view class="" :style="{'--color':vuex_config.themeColor1}">
		<view class="index" v-if="dataList.length>0">
			<view class="list">
				<view class="item " :class="[index == current?'active':'']" @click="change(index)"
					v-for="(item,index) in dataList" :key='index'>
					<text>{{item.name}}</text>
					<view class="price">
						<text class="p-icon">￥</text>
						<text>{{$price(item.amount)}}</text>
					</view>
				</view>
				<view class="mode">
					<view :class="['btn',typecurrent == index?'active':''] " v-for="(item,index) in typeList"
						:key='index' @click="typechange(index)">{{item.name}}
					</view>
				</view>
			</view>
			<view class="footer">
				<view class="f-left">
					<text>待支付：</text>
					<view class="price red">
						<text class="p-icon">￥</text>
						<text>{{$price(dataList[current].amount)}}</text>
					</view>
				</view>
				<view class="f-right" :class="[isDo?'disable':'user']" @click="godetail">{{isDo?'查看进程':'立即付款'}}</view>
			</view>
		</view>
		<sww-login></sww-login>
		<sww-coupon v-model="couponItem" :prodPrice="dataList[current].amount" class_id="0">
			<view class="couponbtn" @click="payorder(coupon)">确定</view>
		</sww-coupon>
	</view>

</template>

<script>
	import {
		resGet
	} from '@/common/http.request'
	import store from "@/store";
	import {
		formatDate
	} from '@/utils/moment'
	export default {
		data() {
			return {
				dataList: [],
				typeList: [],
				typecurrent: 0,
				id: '',
				current: 0,
				isDo: false,
				couponItem: {
					price: 0,
					name: '无可用',
					show: false
				},
			}
		},
		onLoad(option) {
			this.id = option.id
			this.initPage()
		},
		methods: {
			initPage() {
				this.$login('initPage').then(() => {
					this.$loading()
					this.gettype()
					this.$resPost('GetRhythmOrder', {}).then(({
						data
					}) => {
						let newTime = new Date().getTime()
						let endTime = new Date(data.end_date || '').getTime()
						if (newTime < endTime) {
							this.id = data.num
							this.isDo = true
						} else {
							this.isDo = false
						}
						resGet('GetItem', {
							id: this.id
						}, {}, {
							baseUrl: 'https://ldy.lumachina.net'
						}).then(res => {
							this.$resPost('GetPackageSettingsList', {
								business_id: this.vuex_business.pk_id,
								code:this.id
							}).then(res => {
								this.dataList = res.data
								this.$hide()
							})

						})
					}).catch(err => {
						this.$hide()
						this.$toast(err)
					})


				});
			},
			gettype() {
				this.$resPost('GetRhythmModeList', {
					business_id:this.vuex_business.pk_id
				}).then(res => {
					this.typeList = res.data
				}).catch(err => {
					this.$toast(err)
				})
				this.$resPost('GetUsersInfo').then(res => {
					this.$u.vuex('vuex_user', res.data);
				}).catch(err => {
					this.$toast(err)
				})
			},
			change(idx) {
				this.current = idx
			},
			typechange(idx) {
				this.typecurrent = idx
				if (this.isDo) {
					resGet('GetItem', {
						id: this.id
					}, {}, {
						baseUrl: 'https://ldy.lumachina.net'
					}).then(res => {
						let data = res.data
						this.$resPost('UpdateMode', {
							id: this.id,
							...data,
							Frequency: this.typeList[this.typecurrent].frequency,
							Intensity: this.typeList[this.typecurrent].intensity,
						}, {}, {
							baseUrl: 'https://ldy.lumachina.net'
						}).then(() => {}).catch(err => {
							this.$toast('设备故障,启动失败')
						})
					}).catch((err) => {
						this.$toast(err)
					})
				}
			},
			godetail() {
				if (this.isDo) {
					this.$linkTo(`/package/RhythmicInstrument/operation/index?id=${this.id}`,
						'reLaunch')
					return
				}

				if (this.couponItem.len > 0) {
					this.couponItem.show = true
				} else {
					this.payorder()
				}
			},
			payorder(val) {
				if (val == 'coupon') {
					this.couponItem.show = false
				}
				this.pay_type = this.vuex_user.member_status == '0'?1:this.vuex_user.member_status == '1' && this.vuex_user.residue_degree <= 0 ? 1 : 8
				let time = new Date().getTime()
				let endtime = time + (this.dataList[this.current].time * 60 * 1000)
				let params = {
					type: this.dataList[this.current].pk_id,
					plate_num: this.id,
					money: this.dataList[this.current].amount,
					start_date: formatDate(new Date(time), 'YYYY-MM-DD HH:mm:ss'),
					end_date: formatDate(new Date(endtime), 'YYYY-MM-DD HH:mm:ss'),
					coupon_id: this.couponItem.pk_id || 0,
					coupon: this.couponItem.price || 0,
					pay_type: this.pay_type,
				}
				let type = this.typeList[this.typecurrent]
				this.$loading()
				this.wxPay(params, this.pay_type).then((res) => {
					this.$hide()
					this.$linkTo(
						`/package/RhythmicInstrument/PaymentCompleted/index?id=${this.id}&Frequency=${type.frequency}&Intensity=${type.intensity}`,
						'reLaunch')
				}).catch((err) => {
					this.$hide()
					console.log(err)
					this.$toast('支付失败')
				})
			},
			// #ifdef H5 || MP-WEIXIN
			wxPay(obj, type) {
				return new Promise((resolve, reject) => {
					let params = {
						mch_id: store.state.vuex_business.mchid,
						body: store.state.vuex_business.name,
						sign_key: store.state.vuex_business.payment_key,
						...obj
					}
					// #ifdef H5
					params = {
						...params,
						openid: store.state.vuex_user.openid,
						appid: store.state.vuex_business.appid,
					}
					// #endif
					// #ifdef MP-WEIXIN
					params = {
						...params,
						openid: store.state.vuex_user.small_routine,
						appid: store.state.vuex_business.appid,
					}
					// #endif
					this.$resPost('AddRhythmPayCreateOrder', params).then(({
						data
					}) => {
						if (type == '1' && this.dataList[this.current].amount - this.couponItem.price >
							0) {
							this.payOrder(data).then((res) => {
								resolve(res)
							}).catch((err) => {
								reject()
							})
						} else {
							this.$resPost('UpdateRhythmPayStatus', {
								order_no: data.order_no,
								pay_status: 1,
								pay_type: type
							}).then((res) => {
								resolve(res)
							}).catch(() => {
								reject()
							})
						}
					}).catch((err) => {
						reject()
					})
				})
			},
			// #endif
			/**
			 * h5端支付
			 */
			// #ifdef H5
			payOrder(payParams) {
				return new Promise((resolve, reject) => {
					const onBridgeReady = () => {
						WeixinJSBridge.invoke('getBrandWCPayRequest', {
							"appId": payParams.appId, //公众号名称，由商户传入
							"timeStamp": payParams.timeStamp, //时间戳，自1970年以来的秒数
							"nonceStr": payParams.nonceStr, //随机串
							"package": payParams.package,
							"signType": payParams.signType, //微信签名方式：
							"paySign": payParams.paySign //微信签名
						}, function(res) {
							if (res.err_msg == "get_brand_wcpay_request:ok") {
								// 使用以上方式判断前端返回,微信团队郑重提示：
								//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
								this.$resPost('UpdateRhythmPayStatus', {
									order_no: payParams.order_no,
									pay_status: 1,
									pay_type: 1
								})
								resolve()
							} else {
								reject()
							}
						});
					}
					if (typeof WeixinJSBridge == "undefined") {
						if (document.addEventListener) {
							document.addEventListener('WeixinJSBridgeReady', onBridgeReady(), false);
						} else if (document.attachEvent) {
							document.attachEvent('WeixinJSBridgeReady', onBridgeReady());
							document.attachEvent('onWeixinJSBridgeReady', onBridgeReady());
						}
					} else {
						onBridgeReady();
					}
				})
			},
			// #endif
			/**
			 * 微信小程序端:微信支付、环迅支付
			 */
			// #ifdef MP-WEIXIN
			payOrder(params) {
				conso.elog('pass', params)
				return new Promise((resolve, reject) => {
					wx.requestPayment({
						'timeStamp': params.timeStamp,
						'nonceStr': params.nonceStr,
						'package': params.package,
						'signType': params.signType,
						'paySign': params.paySign,
						'success': res => {
							this.$resPost('UpdateRhythmPayStatus', {
								order_no: params.order_no,
								pay_status: 1,
								pay_type: 1
							})
							resolve(res)
						},
						'fail': err => {
							console.log('eeee',err)
							reject(err)
						}
					})
				})
			}
			// #endif

		}
	}
</script>

<style lang="scss" scoped>
	.couponbtn {
		width: 100%;
		height: 80rpx;
		border-radius: 10rpx;
		color: #fff;
		background-color: var(--color);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 20rpx;
	}

	.index {
		.list {
			padding: 8rpx 30rpx 0;
			display: flex;
			flex-direction: column;

			.item {
				width: 100%;
				border-radius: 10rpx;
				height: 132rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				border: 1px solid #EAEAEA;
				font-size: 30rpx;
				color: #303133;
				padding: 0 28rpx 0 32rpx;
				margin-bottom: 30rpx;

				&.active {
					background: #1966FF;
					box-shadow: 2rpx 2rpx 8rpx 0 rgba(144, 147, 153, 0.2);
					color: #fff;
				}
			}
		}

		.price {
			display: flex;
			align-items: center;
			font-size: 36rpx;

			.p-icon {
				position: relative;
				bottom: 3rpx;
				font-size: 24rpx;
			}
		}

		.footer {
			width: 690rpx;
			height: 98rpx;
			position: fixed;
			bottom: 0;
			padding: 0 30rpx env(safe-area-inset-bottom);
			box-shadow: 0 -2rpx 2rpx 0 rgba(221, 221, 221, 0.3);
			box-sizing: content-box;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 28rpx;
			color: #303133;

			.f-left {
				display: flex;
				align-items: center;

				.red {
					color: #FF2929;
				}
			}

			.f-right {
				width: 200rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #fff;
				font-size: 32rpx;
				border-radius: 30rpx;

				&.user {
					background-color: #1966FF;
				}

				&.disable {
					background-color: #ccc;
				}
			}
		}

		.mode {
			width: 100%;
			margin-top: 90rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.btn {
				width: 200rpx;
				height: 64rpx;
				background: #f8f8f8;
				border-radius: 10rpx;
				font-size: 28rpx;
				color: #303133;
				display: flex;
				align-items: center;
				justify-content: center;

				&.active {
					background: #1966FF;
					color: #fff;
				}
			}
		}
	}
</style>
